//
//  PaperBoardOrderViewController.m
//  ForestPack
//
//  Created by 骆锴 on 2018/7/17.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "PaperBoardOrderViewController.h"
#import "ModuleSelectView.h"
#import "PaperBoardListCell.h"
#import "FilterView.h"
#import "OrderPaperBoardViewController.h"
#import <MJRefresh.h>


@interface PaperBoardOrderViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) ModuleSelectView *moduleView;
@property (nonatomic, strong) UIButton *shadowBtn;
@property (nonatomic, strong) FilterView *filterView;

@property (nonatomic, strong) NSMutableArray *filterArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *orderByArray;

@property (nonatomic, copy)   NSArray *stackArr;

@property (nonatomic, copy)   NSString *stack;
@property (nonatomic, copy)   NSString *orderBy;
@property (nonatomic, copy)   NSString *keyword;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@end

@implementation PaperBoardOrderViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.moduleView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self setTableView];
    [self setSelectView];
    [self setFilterView];
}

- (void)initData {
    self.dataArray = [NSMutableArray array];
    self.orderByArray = [NSMutableArray arrayWithArray:@[@"1",@"0",@"0"]];
    
    self.stackArr = [NSArray array];
    
    self.stack = @"";
    
    self.keyword = @"";
    self.orderBy = @"default desc";
    self.currentPage = 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Methods
- (void)click {
    __weak __typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.shadowBtn.hidden = NO;
        weakSelf.filterView.frame = CGRectMake(SCREEN_WIDTH - ScreenX375(280), 0, ScreenX375(280), SCREEN_HEIGHT);
    }];
}

- (void)hidden {
    __weak __typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.shadowBtn.hidden = YES;
        weakSelf.filterView.frame = CGRectMake(SCREEN_WIDTH, 0, ScreenX375(280), SCREEN_HEIGHT);
    }];
}

- (void)setNavBar {
    UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(342, 31,20 , 22)];
    [selectBtn setImage:[UIImage imageNamed:@"筛选"] forState:UIControlStateNormal];
    selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
    [selectBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *selectItem = [[UIBarButtonItem alloc] initWithCustomView:selectBtn];
    self.navigationItem.rightBarButtonItem = selectItem;
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 14, 44)];
    [backBtn setImage:[UIImage imageNamed:@"返回白色"] forState:UIControlStateNormal];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIButton *factoryBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    [factoryBtn setTitle:@"厂区" forState:UIControlStateNormal];
    [factoryBtn setImage:ImageWithName(@"多边形1拷贝1") forState:UIControlStateNormal];
    [factoryBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -WIDTH(factoryBtn.imageView), 0, WIDTH(factoryBtn.imageView))];
    [factoryBtn setImageEdgeInsets:UIEdgeInsetsMake(0, WIDTH(factoryBtn.titleLabel), 0, -WIDTH(factoryBtn.titleLabel))];
    [factoryBtn addTarget:self action:@selector(selectFactory) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *factoryItem = [[UIBarButtonItem alloc] initWithCustomView:factoryBtn];
    
    self.navigationItem.leftBarButtonItems = @[backItem,factoryItem];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 52, 30)];
    UIImageView *leftImg = [[UIImageView alloc] initWithFrame:CGRectMake(20, 4, 22, 22)];
    leftImg.image = [UIImage imageNamed:@"搜索"];
    [leftView addSubview:leftImg];
    UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(244), 30)];
    searchField.placeholder = @"搜索您需要的包装设计";
    searchField.layer.cornerRadius = ScreenX375(15);
    searchField.clipsToBounds = YES;
    searchField.backgroundColor = [UIColor whiteColor];
    searchField.leftViewMode = UITextFieldViewModeAlways;
    searchField.leftView = leftView;
    searchField.font = Kfont(13);
    self.navigationItem.titleView = searchField;
}

- (void)setTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT-ScreenX375(94))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];

    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)headerRefresh {
    _currentPage = 1;
    [self getData];
    [self.tableView.mj_header endRefreshing];
    self.tableView.mj_footer.hidden = NO;
}

- (void)footerRefresh {
    if (_currentPage < _totalPage) {
        
        _currentPage++;
        [self getData];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
    }else{
        
        [HttpManager showNoteMsg:@"已经到底啦"];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden = YES;
    }
}

- (void)getData {
    NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"factory_id":kNSUDefaultReadKey(@"FactoryId"),@"keyword":_keyword,@"orderBy":_orderBy,@"page":[NSNumber numberWithInteger:_currentPage]}];
    if (_stack.length > 0) {
        [parameter setObject:_stack forKey:@"stack"];
    }
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/cardboard_index",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSError *error = nil;
            if (self.currentPage == 1) {
                [self.dataArray removeAllObjects];
            }
            self.totalPage = [successResponse[@"data"][@"last_page"] integerValue];
            for (NSDictionary *dict in successResponse[@"data"][@"data"]) {
                BoardListModel *model = [[BoardListModel alloc] initWithDictionary:dict error:&error];
                model.boardId = dict[@"id"];
                [self.dataArray addObject:model];
            }
            if ([successResponse[@"data"][@"data"] count] == 0) {
                [HttpManager showNoteMsg:@"暂无数据"];
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}


- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setFilterView {
    _shadowBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _shadowBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    _shadowBtn.hidden = YES;
    [_shadowBtn addTarget:self action:@selector(hidden) forControlEvents:UIControlEventTouchUpInside];
    [kKeyWindow addSubview:_shadowBtn];
    
    _filterArray = [NSMutableArray arrayWithObjects:@{@"title":@"纸板堆叠层数",@"dataArray":[NSMutableArray array]}, nil];
    _filterView = [[FilterView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, ScreenX375(280), SCREEN_HEIGHT)];
    __weak __typeof(self) weakSelf = self;
    _filterView.backClick = ^{
        [weakSelf hidden];
    };
    _filterView.doneClick = ^(NSArray *array) {
        [weakSelf hidden];
        if ([array[0] integerValue] < weakSelf.stackArr.count) {
            weakSelf.stack = [NSString stringWithFormat:@"%@",weakSelf.stackArr[[array[0] integerValue]][@"material_leng"]];
        }else {
            weakSelf.stack = @"";
        }
        [weakSelf.tableView.mj_header beginRefreshing];
    };
    [_filterView modelArrayForView:_filterArray];
    [kKeyWindow addSubview:_filterView];
    
    [self getNum];
}

- (void)selectFactory {
    if (!self.moduleView) {
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/factorys",REQUESTHEADER] andParameter:nil success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
            if ([status isEqualToString:@"1"]) {
                self.moduleView = [[ModuleSelectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                self.moduleView.isSelectFactory = YES;
                __weak __typeof(self) weakSelf = self;
                self.moduleView.selectClick = ^{
                    weakSelf.moduleView.hidden = YES;
                    [weakSelf.tableView.mj_header beginRefreshing];
                };
                [kKeyWindow addSubview:self.moduleView];
                [self.moduleView modelArrayForView:successResponse[@"data"]];
            }else {
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    }else {
        self.moduleView.hidden = NO;
    }
}

-(void)setSelectView{
    UIView *selectView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(30))];
    selectView.backgroundColor = REXADECIMALCOLOR(@"#eeeeee");
    NSArray *title = [[NSArray alloc] initWithObjects:@"综合  ",@"销量  ",@"发布时间  ",nil];
    CGFloat width = SCREEN_WIDTH / title.count;
    for (int i = 0; i < 3 ; i++) {
        UIButton *titleBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 0, width, ScreenX375(30))];
        [titleBtn setTitle:title[i] forState:UIControlStateNormal];
        [titleBtn setImage:[UIImage imageNamed:@"多边形1拷贝2"] forState:UIControlStateNormal];
        [titleBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -WIDTH(titleBtn.imageView), 0, WIDTH(titleBtn.imageView))];
        [titleBtn setImageEdgeInsets:UIEdgeInsetsMake(0, WIDTH(titleBtn.titleLabel) * 0.8, 0, -WIDTH(titleBtn.titleLabel) * 0.8)];
        titleBtn.titleLabel.font = Kfont(14);
        [titleBtn setTitleColor:RGBACOLOR(153, 153, 153, 1) forState:UIControlStateNormal];
        titleBtn.tag = 100 + i;
        [titleBtn addTarget:self action:@selector(orderBySelect:) forControlEvents:UIControlEventTouchUpInside];
        [selectView addSubview:titleBtn];
    }
    [self.view addSubview:selectView];
}

- (void)orderBySelect:(UIButton *)button {
    NSInteger tag = button.tag - 100;
    if ([_orderByArray[tag] integerValue] == 1) {
        [button setImage:[UIImage imageNamed:@"多边形1拷贝2"] forState:UIControlStateNormal];
        if (tag == 0) {
            _orderBy = @"default asc";
        }else if (tag == 1) {
            _orderBy = @"volume asc";
        }else {
            _orderBy = @"create_at asc";
        }
        
        [_orderByArray replaceObjectAtIndex:tag withObject:@"0"];
    }else {
        [button setImage:[UIImage imageNamed:@"多边形1拷贝"] forState:UIControlStateNormal];
        if (tag == 0) {
            _orderBy = @"default desc";
        }else if (tag == 1) {
            _orderBy = @"volume desc";
        }else {
            _orderBy = @"create_at desc";
        }
        
        [_orderByArray replaceObjectAtIndex:tag withObject:@"1"];
    }
    [self.tableView.mj_header beginRefreshing];
}

#pragma NetWork
- (void)getNum{
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/cardboard_leng",REQUESTHEADER] andParameter:nil success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dict in successResponse[@"data"]) {
                [array addObject:[NSString stringWithFormat:@"%@",dict[@"material_leng"]]];
            }
            NSDictionary *dic = @{@"title":@"纸板堆叠层数",@"dataArray":array};
            [self.filterArray replaceObjectAtIndex:0 withObject:dic];
            [self.filterView modelArrayForView:self.filterArray];
            self.stackArr = successResponse[@"data"];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

#pragma TableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PaperBoardListCell *cell = [PaperBoardListCell cellWithTableView:tableView andIndexPath:indexPath];
    [cell initWithModel:_dataArray[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ScreenX375(108);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BoardListModel *model = _dataArray[indexPath.row];
    OrderPaperBoardViewController *vc = [[OrderPaperBoardViewController alloc] init];
    vc.productId = model.boardId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    _keyword = textField.text;
    [self.tableView.mj_header beginRefreshing];
    [textField resignFirstResponder];
    return NO;
}

@end
